<template>
<div>
	<!-- {{componentObj}} -->
	<div class="editPage" :style="{zIndex:dialogTableVisible?'1801':''}">
		<div class="edit-tool">
			<div class="tools">
				<div v-for="(item, idx) in tools" :key="idx">
					<h3>{{item.typeName}}</h3>
					<div class="design-tool" :class="citem.doclick ? '' : 'is-disabled'" v-for="(citem, cidx) in item.typeList" :key="cidx">
						<el-tooltip class="item" effect="dark" :disabled="(citem.tooltip !='' || !citem.doclick ) ? false : true" :content="citem.tooltip ||citem.changeToolTip" placement="right">
							<div class="design-tool-tip" :class="designtype == citem.designtype ? 'is-selected' : ''" @click="citem.doclick && selTool(citem.designtype)">
								<i class="iconfont" :class="citem.iconname"></i>
								<div>{{citem.name}}</div>
							</div>
						</el-tooltip>
					</div>
				</div>
			</div>
		</div>
		<div class="edit-main">
			<div class="design-box">
				<div class="design-main">
					<!-- @start="isDragging = true" -->
					<draggable class="list-group" tag="ul"
						v-model="selComponents"
						v-bind="dragOptions"
						draggable=".draggableItem"
						@start="start"
						@end="isDragging = false"
						:move='allow'
						@change="changedraggable(selComponents)"
					>
					<!-- @change="allow" -->
						<!-- <transition-group type="transition" name="flip-list"> -->
							
							<li class="list-group-item undraggable" :class="['is'+selItem.designtype, {draggableItem : selItem.designtype != 'DesignConfig'}]" :style="(selItem.designtype == 'DesignBackground' ? {position: 'absolute', zIndex: 0, top: '64px'}: (current == selItem.itemId ? {zIndex: 3}: {zIndex: 1}))" v-for="(selItem, selIdx) in selComponents" :key="'my-name'+selIdx" >
								<div class="design-item">
									<i class="el-icon-circle-plus icon-btn icon-top" v-if="selItem.designtype != 'DesignConfig'" @click.stop="boolbarShowHandle('top', selItem)"></i>
									<i class="el-icon-circle-plus icon-btn icon-bottom" v-if="selItem.designtype != 'DesignConfig'" @click.stop="boolbarShowHandle('bottom', selItem)"></i>
									<div>
										<el-popover
											v-if="selItem.designtype != 'DesignConfig' && selItem.designtype != 'DesignBackground'"
											placement="left"
											width="160"
											trigger="click"
											v-model="selItem.visible"
											>
											<p>确定删除该组件吗？</p>
											<div style="text-align: right; margin-top: 10px">
												<el-button size="mini" type="text" @click.stop="selItem.visible = false">取消</el-button>
												<el-button type="primary" size="mini" v-intervalclick='{func:delHandle,time:1000,selItem}'>确定</el-button>
											</div>
											<i class="el-icon-error icon-btn icon-right" slot="reference"></i>
										</el-popover>
									</div>
									<!-- 背景所用 -->
									<div v-if="selItem.designtype != 'DesignConfig' && selItem.designtype == 'DesignBackground'" class="isDesignBackgroundEdit" >编辑<i class="el-icon-edit" @click.stop="selectHandle(selItem)"></i>——
										<el-popover
											placement="right"
											width="160"
											trigger="click"
											v-model="selItem.visible"
											>
											<p>确定删除该组件吗？</p>
											<div style="text-align: right; margin-top: 10px">
												<el-button size="mini" type="text" @click.stop="selItem.visible = false">取消</el-button>
												<el-button type="primary" size="mini" v-intervalclick='{func:delHandle,time:1000,selItem}'>确定</el-button>
											</div>
											<i class="el-icon-delete" slot="reference"></i>
										</el-popover>
									</div>
									
									<div @click="selectHandle(selItem)">
										
										<!-- 头部 -->
										<form-config v-if="selItem.designtype == 'DesignConfig'" ref="childRules" :header-form="selItem" :current="current" @childChange="parentChangeStatus"></form-config>
										<!-- 富文本 -->
										<form-design-richeditor v-if="selItem.designtype == 'FormDesignRicheditor'" :richeditor-form="selItem" :current="current" @childChange="parentChangeStatus"></form-design-richeditor>
										<!-- 标题 -->
										<form-title v-if="selItem.designtype == 'DesignTitle'" ref="childRules" :title-form="selItem" :current="current" @childChange="parentChangeStatus"></form-title>
										<!-- 图片 -->
										<form-image v-if="selItem.designtype == 'DesignImage'" :image-form="selItem" :current="current" @childChange="parentChangeStatus"></form-image>
										<!-- 辅助空白 -->
										<form-white-space v-if="selItem.designtype == 'DesignWhitespace'" :space-form="selItem" :current="current" @childChange="parentChangeStatus"></form-white-space>
										<!-- 背景 -->
										<form-background v-if="selItem.designtype == 'DesignBackground'" :background-form="selItem" :current="current" @childChange="parentChangeStatus"></form-background>
										<!-- 商品 -->
										<form-good-list v-if="selItem.designtype == 'DesignGoodList'" :goodlist-form="selItem" :current="current" @childChange="parentChangeStatus"></form-good-list>
									
									</div>
									<div class="design-edit" :class="boolbarPoistion == 'bottom' ? 'is-bottom' : 'is-top'" v-show="(designtype == selItem.designtype) && selItem.toolbarComponents">
										<h4 class="edit-title"><span>添加组件</span></h4>
										<div class="design-tools" v-for="(ritem, ridx) in tools" :key="ridx">
											<h3>{{ritem.typeName}}</h3>
											<div class="design-tool" :class="critem.doclick ? '' : 'is-disabled'" v-for="(critem, cridx) in ritem.typeList" :key="cridx">
												<el-tooltip class="item" effect="dark" :disabled="(critem.tooltip !='' || !critem.doclick ) ? false : true" :content="critem.tooltip ||critem.changeToolTip" placement="bottom">
													<div class="design-tool-count" :class="designtype == critem.designtype ? 'is-selected' : ''" @click="critem.doclick && selTool(critem.designtype, selItem.itemId, boolbarPoistion)">
														<i class="iconfont" :class="critem.iconname"></i>
														<p>{{critem.name}}</p>
													</div>
												</el-tooltip>
											</div>
										</div>
									</div>
								</div>
							</li>
						<!-- </transition-group> -->
					</draggable>
				</div>
				
			</div>
		</div>
	</div>
	<div class="saveWrap">
		<el-button size="medium" @click.native="saveHandle('preview')">预览</el-button>
		<el-button size="medium" @click.native="saveHandle">保存</el-button>
	</div>
</div>
</template>

<script>
import draggable from 'vuedraggable';
import {createRandomId} from '@/tools/util';
import FormConfig from './FormConfig/FormConfig';
import FormDesignRicheditor from './FormDesignRicheditor/FormDesignRicheditor';
import FormTitle from './FormTitle/FormTitle';
import FormGoodList from './FormGoodList/FormGoodList';
import FormWhiteSpace from './FormWhiteSpace/FormWhiteSpace';
import FormBackground from './FormBackground/FormBackground';
import FormImage from './FormImage/FormImage';
import {undraggable} from "@/tools/util";
import debounce from '@/tools/debounce';
import {http, post} from '@/tools/http'
export default {
	components: {draggable,FormConfig,FormDesignRicheditor,FormTitle,FormGoodList,FormWhiteSpace,FormBackground,FormImage},
	display: "Transition",
	name: 'FormTemplateDesign',
	order: 6,
	data () {
		return {
			isDragging: false,
			tools: this.globalVar.tools,
			current: 0,
			selComponents: [],
			designtype: '',
			boolbarPoistion: '',
			selgoodIds: [],
    	}
  	},
  	async created(){
		if(this.$route.query.pageId){
			let res = await this.findPage(this.$route.query.pageId) || [];
			this.selComponents = res.selComponents || [];
		}
		if(this.selComponents.length) {
			this.selectHandle(this.selComponents[0]);
			this.selComponents.map((item) => {
				if(item.designtype  == "DesignBackground" ){
					this.findToolsObj(item.designtype);
				} 
			});
		}else this.selTool('DesignConfig');
	},
	methods:{
		start(e){
			e.item.style.transform = null;
			this.isDragging = false;
		},
		findToolsObj(type, isDoclickBoolean){
			this.tools.map((item) => {
				item.typeList.map((citem) => {
					if(citem.designtype == type){
						citem.doclick = false || isDoclickBoolean;
					}
				})
			})
			// console.log('this.tools',this.tools)
		},
		selTool(type, itemId, boolbarPoistion){
			let designPreVal = JSON.parse(JSON.stringify(this.globalVar.designPreVal));
			let selComponents = JSON.parse(JSON.stringify(this.selComponents));
			let obj = {};
			if(type == "DesignBackground"){
				this.findToolsObj(type);
			}
			designPreVal.map((item) => {
				if(item.designtype == type ){
					(!item.itemId) && (item.itemId = createRandomId());
					obj = item;
				} 
			});
			if(itemId && boolbarPoistion){
				selComponents.map((sitem, sidx) => {
					if(sitem.itemId == itemId){
						if(boolbarPoistion == 'top'){
							this.selComponents.splice(sidx, 0, obj)
						}else{
							this.selComponents.splice(sidx+1, 0, obj)
						}
					}
				});
				this.$nextTick(() => {
					this.getScrollPosition(obj);
				})
			}else{
				this.selComponents.push(obj);
				this.$nextTick(() => {
					this.getScrollPosition(obj);
				})
			}
			this.selectHandle(obj);
			this.designtype =  type; 
		},
		getScrollPosition(newitem){
			let selComponents = JSON.parse(JSON.stringify(this.selComponents));
			for(let i = selComponents.length-1;i >= 0 ;i--){
				if(selComponents[i].itemId == newitem.itemId){
					let lidom = document.querySelectorAll(".list-group-item")[i]
					lidom.scrollIntoView(true)
				} 
			}
		},
		selectHandle(selItem){
			this.current = selItem.itemId;
			this.selComponents.map((item) => {
				// item.toolbarEdit = false;
				item.toolbarComponents = false;
			});
			selItem.toolbarEdit = true;
			this.$store.commit("setComponentObj", selItem);
			this.designtype = selItem.designtype;
		},
		saveHandle(type){
			this.$nextTick().then(()=>{
				let that = this;
				let rulesArr = this.$refs.childRules;
				let errorArr = [];
				let flag = true;
				rulesArr.map((item, idx) => {
					let form = rulesArr[idx].$refs.form;
					form.validate((valid) => {
						if(!valid) errorArr.push(item) && (flag = false)
					})
				})
				for(let i = errorArr.length-1; i>=0; i--){
					let arr = errorArr[i];
					let form = arr.$refs.form;
					// let form = errorArr[i];
					// console.log("form------", errorArr[0].validateForm)
					// let modelObj = form.$refs.form.model;
					let modelObj = form.model;
					form.validate((valid) => {
						if(!valid) {
							arr.validateForm();
							that.getScrollPosition(modelObj);
							that.selectHandle(modelObj);
							return
						}
					})
				}
				if(!errorArr.length && flag){
					let params = {
						selComponents: JSON.stringify(this.selComponents)
					}
					// console.log('this.selComponents', this.selComponents);
					post('/balabala/savePage',params).then(function (result) { 
						let res = result.data;
						if(type == 'preview') {
							that.$router.push({path: '/Preview', query: {pageId: res.pageId}})
						} else{
							window.location.href = res.returnUrl;
						}
					})
				}
			})
		},
		allow(evt) {
			this.designtype = evt.draggedContext.element.designtype;
			this.current = evt.draggedContext.element.itemId;
			this.$store.commit("setComponentObj", evt.draggedContext.element);
		},
		changedraggable(e){
			// console.log('e', e)
			// this.selComponents = e;
		},
		delHandle(selItem){
			selItem.visible = false;
			let that = this;
			let newitem;
			let newArr = JSON.parse(JSON.stringify(that.selComponents));
			let delId = newArr[newArr.length - 1].itemId;
			// console.log('delId', delId);
			if(that.selComponents.length == 1){
				that.current == that.selComponents[0].itemId;
				newitem = that.selComponents[0];
			}else{
				newArr.map((item, idx) => {
					if((selItem.itemId == newArr[idx].itemId) && (selItem.itemId != delId)){
						newitem = newArr[idx+1];
						that.current = newitem.itemId;
						newArr.splice(idx, 1);
					}else if((selItem.itemId == newArr[idx].itemId) && (selItem.itemId == delId)){
						newitem = newArr[idx-1];
						that.current = newitem.itemId;
						newArr.splice(idx, 1)
					}
				});
				that.selComponents = newArr;
			}
			// console.log('current', that.current);
			// console.log('currentselComponents', that.selComponents);
			if(selItem.designtype == "DesignBackground"){
				this.findToolsObj(selItem.designtype, true);
			}
			that.selectHandle(newitem);
			that.$nextTick(() => {
				that.getScrollPosition(newitem);
			})
		},
		parentChangeStatus(form){
			this.$store.commit("setComponentObj", form)
			// console.log("父form", form);
		},
		boolbarShowHandle(position, selItem){
			this.boolbarPoistion = position;
			this.selComponents.map((item, idx) => {
				item.toolbarEdit = false;
				item.toolbarComponents = false;
			});
			selItem.toolbarComponents = true;
			this.designtype =  selItem.designtype;
			this.$store.commit("setComponentObj", selItem);
		},
		findPage(id){
			let params = {
				pageId: id
			}
			return this.$store.dispatch("findPage", params);
		}
	},
	computed: {
		dragOptions() {
			return {
				animation: 0,
				group: "description",
				disabled: false,
				ghostClass: "ghost",
				// handle: ".design-item-list"
			};
		},
		componentObj () {
			return this.$store.getters.componentObj
		},
		dialogTableVisible () {
			return this.$store.getters.dialogTableVisible
		},
	},
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@import "../../../static/css/style.less";

.iconfont{
  font-size: 28px;
}
.list-group,
.list-group-item{
	position: relative;
	width: 100%;
	z-index: 2;
}
</style>
